from fastapi import APIRouter, Depends, HTTPException
from indicapp.models import AsyncSessionFactory
from sqlalchemy.ext.asyncio import AsyncSession
from indicapp.func import process_tasks_concurrently
from common.log import LOG, LogLevel
from common.utils import DBUtil


router = APIRouter(prefix="/indic", tags=["组织指标数据"])


# 函数依赖（获取异步数据库会话）
async def get_asyncsession():
    session = AsyncSessionFactory()
    try:
        yield session
    finally:
        await session.close()


@router.get('/initma', description="初始化均线ma数据库")
async def init_ma(session: AsyncSession=Depends(get_asyncsession)):
    try:
        async with session.begin():
            # 1. 删除现有的ma数据表
            await DBUtil(session).drop_all_tables_startwith("ma")
            # 2. 从本地获取所有主力合约代码
            result = await DBUtil(session).get_main_contracts()
            symbols = result.scalars().fetchall() # 取第一列代码
            # 3. 需要遍历所有k线周期和均线周期
            periods = ["1", "5", "30", "120"]  # 定义需要获取的周期，单位为min
            ma_periods = ["5", "10", "20", "40", "60"]  # 需要计算的MA周期
            # 4. 创建所有任务，并并发执行
            await process_tasks_concurrently(symbols, periods, ma_periods)
            return {"message": "初始化均线MA数据库成功！"}
    except RuntimeError as e:
        LOG(LogLevel.ERROR) << f"{str(e)}" << "\n"
        raise HTTPException(status_code=500, detail="部分均线数据初始化失败！")
    except Exception as e:
        LOG(LogLevel.ERROR) << f"初始化均线数据库失败：{str(e)}" << "\n"
        raise HTTPException(status_code=500, detail="初始化均线数据库失败，请服务端查看原因！")